import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder

# 读取数据
df = pd.read_csv('F:/projdvn/car_prices_conversion.csv')

# 处理缺失值
df.dropna(subset=['sellingprice'], inplace=True)

# 特征工程
categorical_cols = ['make','model', 'trim', 'body', 'color', 'interior','seller', 'transmission']
label_encoders = {}
for col in categorical_cols:
    le = LabelEncoder()
    df[col] = le.fit_transform(df[col])
    label_encoders[col] = le

# 划分特征和目标变量
X = df.drop('sellingprice', axis=1)
y = df['sellingprice']

# 先对分类变量进行编码，再处理缺失值（使用均值填充数值型特征）
imputer = SimpleImputer(strategy='mean')
X = imputer.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建线性回归模型并训练
model = LinearRegression()
model.fit(X_train, y_train)

# 预测
y_pred = model.predict(X_test)

# 评估模型
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"均方误差: {mse}")
print(f"决定系数: {r2}")

# 预测新数据（这里假设你有新的数据，你可以根据实际情况修改这部分代码）
new_data = df.sample(5)  # 示例，随机选取 5 行数据作为新数据
new_data_pred = model.predict(new_data.drop('sellingprice', axis=1))
print("新数据预测结果:")
for i in range(len(new_data_pred)):
    print(f"预测价格: {new_data_pred[i]}, 实际价格: {new_data.iloc[i]['sellingprice']}")
   

    import matplotlib.pyplot as plt
import numpy as np

# 计算平均绝对误差（MAE）
mae = np.mean(np.abs(y_test - y_pred))

# 计算均方根误差（RMSE）
rmse = np.sqrt(mse)

print(f"平均绝对误差（MAE）: {mae}")
print(f"均方根误差（RMSE）: {rmse}")

# 绘制预测值与真实值的散点图
plt.scatter(y_test, y_pred)
plt.xlabel('真实值')
plt.ylabel('预测值')
plt.title('预测值与真实值的散点图')
plt.show()

# 设定误差阈值（例如 1000），计算在该阈值范围内的样本比例作为类似正确率的指标
threshold = 1000
correct_predictions = np.sum(np.abs(y_test - y_pred) <= threshold)
accuracy_like = correct_predictions / len(y_test)

print(f"在误差阈值 {threshold} 范围内的样本比例（类似正确率）: {accuracy_like}")

import numpy as np
import pandas as pd
import shap
from sklearn.linear_model import LinearRegression
# 假设X_pred是你的预测数据
X_pred = pd.DataFrame
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# 假设你的数据集是X和y
# X是特征矩阵，y是目标变量
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([3, 7, 11, 15])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)

X_pred = X_test
y_pred = model.predict(X_pred)

print("预测结果：", y_pred)
import numpy as np
import pandas as pd
import shap
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

# 假设你的数据集是X和y
# X是特征矩阵，y是目标变量
X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([3, 7, 11, 15])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)

explainer = shap.LinearExplainer(model, X_test)
shap_values = explainer.shap_values(X_test)

shap.summary_plot(shap_values, X_test)
plt.show()